import Vue from 'vue'
import VueRouter from 'vue-router'

/* eslint-disable */
import HomeApp from '../views/HomeApp.vue'
import Login from '../views/login/index.vue'

import strings from '@/util/strings.js'
const defaultSettings = require('../settings.js')
// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
// eslint-disable-next-line import/no-dynamic-require
// const _import = require('./import-' + process.env.NODE_ENV)
// const _import = require.context('.', false, 'import-' + process.env.NODE_ENV)


Vue.use(VueRouter)
// const UserIndex = require('@/views/sys/user/index')

// 全局路由
const constantRoutes = [
  { path: defaultSettings.pathLogin, component: Login, name: 'login', meta: { title: '登录',allowBack: false } },
]

let mainRoute = {
  path: '/home',
  component: HomeApp,
  meta: { title: '主页',allowBack: false },
  children: []
}

import moduleList from '@/util/const/moduleList.js'
let moduleItem
let menuList = []
let menuOne
Object.keys(moduleList).forEach(moduleKey => {
  moduleItem = moduleList[moduleKey]
  moduleItem.menuList.forEach(menuItem => {
    menuOne = menuItem
    menuOne.meta = { title: `${moduleItem.moduleName}-${menuItem.title}`}
    menuOne.component = (resolve) => require([`@/views/${menuItem.pathView}`], resolve)
    menuList.push(menuOne)
  })
})
mainRoute.children = menuList

const router = new VueRouter({
  mode: 'history',
  base: defaultSettings.pathRoot,
  scrollBehavior: () => ({ y: 0 }),
  isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
  routes: constantRoutes.concat(mainRoute)
})

router.addRoutes([
  mainRoute
  // { path: '*', redirect: { name: 'PageNotFound' }  }
])

let generateRouter = (menus)  => {
  let routes = []
  menus.forEach(item => {
    let route = null
    if (item.route && item.route.length > 0) {
      route = {
        name: item.name == null ? item.route : item.name,
        path: item.route,
        // component: _import(item.url),
        /*component: () => import(`@/views/${item.url}`),*/
        props: {
          propFlowKey: item.flowKey,
          propParameter: item.parameter
        },
        meta: {
          title: item.title,
          flowKey: item.flowKey
        }
      }
      let routerStr = item.route
      if (routerStr.indexOf('online/report/') != -1) {
        route.component = Report
        route.props.propReportKey = routerStr.substring(routerStr.lastIndexOf('/') + 1)
      } else if (routerStr.indexOf('online/board/') != -1) {
        route.component = Board
        route.props.propReportKey = routerStr.substring(routerStr.lastIndexOf('/') + 1)
      } else if (routerStr.indexOf('online/reportMore') != -1) {
        route.component = ReportMore
        route.props.propParameter = item.parameter
      } else if (strings.isNotBlank(item.viewKey)) {
        route.component = indexModel
        route.props.propViewKey = item.viewKey
        route.props.propFlowKey = item.flowKey
      } else if (strings.isNotBlank(item.url)) {
        route.component = (resolve) => require([`@/views/${item.url}`], resolve)
      }
      routes.push(route)
    }
    if (item.properties.url && item.properties.url.length > 0) {
      let  url = item.properties.url
      if (url.indexOf('.html') != -1) {// html 页面
        let name = url.replace('.html', '')
        route = {
          name: global.strings.replaceAll(name, '/', ''),
          path: name,
          // component: _import(item.url),
          /*component: () => import(`@/views/${item.url}`),*/
          props: {
          },
          meta: {
            title: item.title,
            flowKey: item.flowKey,
            htmlAddr: item.properties.url
          }
        }
        routes.push(route)
      }else if (url.indexOf('.vue') != -1) {// vue 页面
        let name = url.replace('.vue', '')
        name = global.strings.replaceAll(name, '/', '')
        name = global.strings.replaceAll(name, '-', '')
        route = {
          name: name,
          path: url.replace('.vue', ''),
          component: (resolve) => require([`@/views${url}`], resolve),
          props: {
          },
          meta: {
            title: item.title,
            flowKey: item.flowKey,
            htmlAddr: item.properties.url
          }
        }
        routes.push(route)
      }

    }
    if (item.children && item.children.length > 0) {
      routes = routes.concat(generateRouter(item.children))
    }
  })
  return routes
}

/**
 * 仅考虑二级菜单，将二级菜单加入到路由中
 * @param {Array} menus
 */
function addDynamicRoutes(menus = []) {
  let routes = generateRouter(menus)

  // mainRoute.name = 'main-dynamic'
  mainRoute.children = mainRoute.children.concat(routes)
  router.addRoutes([
    mainRoute
    // { path: '*', redirect: { name: 'PageNotFound' }  }
  ])
}


router.beforeEach((to, from, next) => {
  // 如果是登录或登出，放行
  if (to.path == defaultSettings.pathLogin || to.path == defaultSettings.pathLoginAll || to.path == '/logout') {
    next()
    return
  }

  let token = sessionStorage.getItem('X-Token')
  if (strings.isBlank(token)) {
    next({ path: defaultSettings.pathLogin })
    return
  }

  console.log('beforeEach.to', to)
  console.log('beforeEach.from', from)
  if (to.name == from.name && from.query) {
    Object.keys(from.query).forEach(key => {
      to.meta[key] = from.query[key]
    })
  }

  next()

  let allowBack = true    //    给个默认值true
  if (to.meta.allowBack !== undefined) {
    allowBack = to.meta.allowBack
  }
  if (!allowBack) {
    history.pushState(null, null, location.href)
  }
  localStorage.setItem('allowBack', allowBack)

  return
})
export default router
